package org.marketing.common.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DateUtil {
	private static Logger logger = LoggerFactory.getLogger(DateUtil.class);
	/**
     * private constructor
     */
    private DateUtil() {// prevent instantiation
    }
    
	public static Date addDay(Date date, int days)
	{
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, days);
		Date newDate = calendar.getTime();
		return newDate;
	}
	/**
	 * 当前日期减day天
	 * 
	 * @param day
	 *            天数
	 * @return
	 */
	public static Date subtractDay(int day){
        Calendar c = Calendar.getInstance();
        int temp=0;
        do {
            c.add(Calendar.DAY_OF_YEAR, -1);
            temp++;
        } while (temp!=day);
        
        return c.getTime();
    }
	/**
	 * 当前日期加day工作日天
	 * 
	 * @param day
	 *            天数
	 * @return
	 */
	public static Date addDay(int day){
		Calendar c = Calendar.getInstance();
		int temp=0;
		do {
			c.add(Calendar.DAY_OF_YEAR, 1);
			if(!(c.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY||c.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY)){
				temp++;
			}
		} while (temp!=day);
		
		return c.getTime();
	}
	////////bwt
	/**
	 * 当前日期加day工作日天
	 * 
	 * @return day
	 */
    public static String getNowDate() { 
        Date currentTime = new Date(); 
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
        String dateString = formatter.format(currentTime); 
        return dateString; 
    }
    
	/**
	 * 当前日期加day工作日天
	 * 
	 * @param date
	 *            天
	 * @return day
	 */
    public static String getNowDate(Date date) { 
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(date); 
    } 
    
	/**
	 * 当前日期加day工作日天
	 * 
	 * @param strDate
	 *            天
	 * @return day
	 */
    public static Date dataFormat(String strDate){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        try {  
            date = sdf.parse(strDate); 
        } catch (Exception e) {  
        	logger.error(e.getMessage(),e);
        } 
        return new java.sql.Date(date.getTime());
    }
    
    /**
     * 根据指定日期字符串和指定的格式进行解析并返回日期对象
     * 
     * @param strDate
     * @param format
     * 
     * @return date
     */
    public static Date dateFormat(String strDate, String format){
    	try {  
    		SimpleDateFormat sdf = new SimpleDateFormat(format);
    		
    		return sdf.parse(strDate); 
    	} catch (Exception e) {
    		logger.error("日期格式错误：原因：" + e.getMessage(),e);
    		throw new RuntimeException("日期格式错误：原因：" + e.getMessage(),e); 
    	} 
    }

	/**
	 * <p>
	 * Description: 得到几月后的时间
	 * </p>
	 * 
	 * @param d
	 *            日期
	 * @param month
	 *            天数
	 * @return Date 计算后的日期
	 */
	public static Date getDateAfterMonth(Date d, int month) {
		Calendar now = Calendar.getInstance();
		now.setTime(d);
		// now.set(Calendar.MONTH, now.get(Calendar.MONTH) + month);
		now.add(Calendar.MONTH, month);
		return now.getTime();
	}

	/**
	 * <p>
	 * Description: 获取根据某日期获取当月最大天数
	 * </p>
	 * 
	 * @param d
	 *            日期
	 * @return 当月最大天数
	 */
	public static int getMonthMaxDays(Date d) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(d);
		return cal.getActualMaximum(cal.DATE);
	}

	/**
	 * <p>
	 * Description: 获取根据某日期获取当月最大天数
	 * </p>
	 * 
	 * @param yearMonth
	 *            年月 格式 yyyy-MM
	 * @return 当月最大天数
	 */
	public static int getMonthMaxDaysByMonth(String yearMonth) {
		String tmpYearMonth = yearMonth + "-01";
		Date tmpDate = DateUtil.dataFormat(tmpYearMonth);
		Calendar cal = Calendar.getInstance();
		cal.setTime(tmpDate);
		return cal.getActualMaximum(cal.DATE);
	}

	/**
	 * @param strDate
	 *            日期字符串
	 * @param pattern
	 *            格式化类型
	 * @return 日期
	 */
	public static Date parseDate(String strDate, String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		Date date = new Date();
		try {
			date = sdf.parse(strDate);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return date;
	}

	/**
	 * @param date
	 *            日期
	 * @param pattern
	 *            转换类型
	 * @return 日期字符串
	 */
	public static String formateDate(Date date, String pattern) {
	    if(date != null){
	        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
	        String dateString = formatter.format(date);
	        return dateString;
	    }
		return "";
	}
	/**
	 * @param date
	 *            日期
	 * @param pattern
	 *            转换类型
	 * @return 日期字符串
	 */
	public static String formateString(String date, String pattern) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(pattern);
			if(date != null && !"".equals(date)){
				Date d = sdf.parse(date);
		        return sdf.format(d);
		    }
			return "";
		} catch (Exception e) {
    		logger.error("日期格式错误：原因：" + e.getMessage(),e);
    		throw new RuntimeException("日期格式错误：原因：" + e.getMessage(),e); 
    	} 
	}
	/**
	 * @param l 时间戳
	 * @param pattern 转换类型
	 * @return 日期字符串
	 */
	public static String formateLong(Long l, String pattern) {
	    if(l != null){
	    	Date date = new Date(l);
	        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
	        String dateString = formatter.format(date);
	        return dateString;
	    }
		return "";
	}

	/**
	 * <p>
	 * Description: 得到几天后的时间
	 * </p>
	 * 
	 * @param d
	 *            日期
	 * @param day
	 *            天数
	 * @return Date 计算后的日期
	 */
	public static Date getDateAfter(Date d, int day) {
		Calendar now = Calendar.getInstance();
		now.setTime(d);
		now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
		return now.getTime();
	}

	/**
	 * @param date
	 *            日期
	 * @return 对应的周度
	 */
	public static int getDayOfWeekByDate(Date date) {
		Calendar curDay = Calendar.getInstance();
		curDay.setTime(date);
		return curDay.get(Calendar.DAY_OF_WEEK) - 1;
	}
	
	public static String getWeek(Date date) {      
	    String[] weekOfDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};        
	    Calendar calendar = Calendar.getInstance();      
	    if(date != null){        
	         calendar.setTime(date);      
	    }        
	    int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;      
	    if (w < 0){        
	        w = 0;      
	    }      
	    return weekOfDays[w];    
	}
	
	/** 
     * 时间戳转换成日期格式字符串 
     * @param seconds 精确到秒的字符串 
     * @param formatStr 
     * @return 
     */  
    public static String timeStamp2Date(String seconds,String format) {  
        if(seconds == null || seconds.isEmpty() || seconds.equals("null")){  
            return "";  
        }
        
        if(format == null || format.isEmpty()) {
        	format = "yyyy-MM-dd HH:mm:ss"; 
        } 
        SimpleDateFormat sdf = new SimpleDateFormat(format);  
        return sdf.format(new Date(Long.valueOf(seconds)));  
    } 
    /** 
     * 时间戳转换成日期格式字符串 
     * @param seconds 精确到秒的字符串 
     * @param formatStr 
     * @return 
     */  
    public static String timeStamp2Date(Date seconds,String format) {  
        if(seconds == null /*|| seconds.equals("null")*/){  
            return "";  
        }
        
        if(format == null || format.isEmpty()) {
        	format = "yyyy-MM-dd HH:mm:ss"; 
        } 
        SimpleDateFormat sdf = new SimpleDateFormat(format);  
        return sdf.format(seconds);  
    } 
	/**
	 * @return
	 */
	public static Date getFirstDayOfWeekByDate(Date date) {
		int i = getDayOfWeekByDate(date);
		Date firstDate = null;
		if (0 == i) {
			firstDate = getDateAfter(date, -6);
		} else {
			firstDate = getDateAfter(date, -1 * (i - 1));
		}

		return firstDate;
	}

	/**
	 * @param date
	 *            日期
	 * @return 获取当前日期所在月的最后一天
	 */
	public static Date getLastDayOfMonth(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
		return calendar.getTime();
	}
	
	/**
	 * 
	 * <p>Description: 获取今天是本年的第几周</p>
	 * @param date
	 * @return
	 */
	public static int getWeekOfDate(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.WEEK_OF_YEAR);
	}
	
	
	
	/**
	 * 获取当前时间点
	 * @return
	 */
	public static Date currentDateTime()
    {
        return Calendar.getInstance().getTime();
    }
	
	
	/**
	 * 
	 * <p>Description: 比较时间</p>
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static boolean afterDate(Object date1,Object date2){
	    return ((Date)date1).after((Date)date2);
	}
	
	/**
	 * 
	 * <p>Description: 比较时间</p>
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static boolean beforDate(Object date1,Object date2){
	    return ((Date)date1).before((Date)date2);
	}
	
	/**
     * 根据指定日期对象和指定的格式进行解析并返回日期对象
     * 
     * @param strDate
     * @param format
     * 
     * @return date
     */
    public static Date dateFormatDate(Date date, String format){
    	try {  
    		SimpleDateFormat sdf = new SimpleDateFormat(format);
	        String dateString = sdf.format(date);
    		
    		return sdf.parse(dateString); 
    	} catch (Exception e) {  
    		logger.error(e.getMessage(),e);
    		throw new RuntimeException("日期格式错误：原因：" + e.getMessage(),e); 
    	} 
    }
    
    
    
    /**
     * 变量：日期格式化类型 - 格式:yyyy/MM/dd
     */
	public static final int DEFAULT = 0;
	public static final int YM = 1;

    /**
     * 变量：日期格式化类型 - 格式:yyyy-MM-dd
     * 
     */
    public static final int YMR_SLASH = 11;

    /**
     * 变量：日期格式化类型 - 格式:yyyyMMdd
     * 
     */
    public static final int NO_SLASH = 2;

    /**
     * 变量：日期格式化类型 - 格式:yyyyMM
     * 
     */
    public static final int YM_NO_SLASH = 3;

    /**
     * 变量：日期格式化类型 - 格式:yyyy/MM/dd HH:mm:ss
     * 
     */
    public static final int DATE_TIME = 4;

    /**
     * 变量：日期格式化类型 - 格式:yyyyMMddHHmmss
     * 
     */
    public static final int DATE_TIME_NO_SLASH = 5;

    /**
     * 变量：日期格式化类型 - 格式:yyyy/MM/dd HH:mm
     * 
     */
    public static final int DATE_HM = 6;

    /**
     * 变量：日期格式化类型 - 格式:HH:mm:ss
     * 
     */
    public static final int TIME = 7;

    /**
     * 变量：日期格式化类型 - 格式:HH:mm
     * 
     */
    public static final int HM = 8;
    
    /**
     * 变量：日期格式化类型 - 格式:HHmmss
     * 
     */
    public static final int LONG_TIME = 9;
    /**
     * 变量：日期格式化类型 - 格式:HHmm
     * 
     */
    
    public static final int SHORT_TIME = 10;

    /**
     * 变量：日期格式化类型 - 格式:yyyy-MM-dd HH:mm:ss
     */
    public static final int DATE_TIME_LINE = 12;
	public static String dateToStr(Date date, int type) {
        switch (type) {
        case DEFAULT:
            return dateToStr(date);
        case YM:
            return dateToStr(date, "yyyy/MM");
        case NO_SLASH:
            return dateToStr(date, "yyyyMMdd");
        case YMR_SLASH:
        	return dateToStr(date, "yyyy-MM-dd");
        case YM_NO_SLASH:
            return dateToStr(date, "yyyyMM");
        case DATE_TIME:
            return dateToStr(date, "yyyy/MM/dd HH:mm:ss");
        case DATE_TIME_NO_SLASH:
            return dateToStr(date, "yyyyMMddHHmmss");
        case DATE_HM:
            return dateToStr(date, "yyyy/MM/dd HH:mm");
        case TIME:
            return dateToStr(date, "HH:mm:ss");
        case HM:
            return dateToStr(date, "HH:mm");
        case LONG_TIME:
            return dateToStr(date, "HHmmss");
        case SHORT_TIME:
            return dateToStr(date, "HHmm");
        case DATE_TIME_LINE:
            return dateToStr(date, "yyyy-MM-dd HH:mm:ss");
        default:
            throw new IllegalArgumentException("Type undefined : " + type);
        }
    }
	public static String dateToStr(Date date,String pattern) {
	       if (date == null || date.equals(""))
	    	 return null;
	       SimpleDateFormat formatter = new SimpleDateFormat(pattern);
	       return formatter.format(date);
    } 

    public static String dateToStr(Date date) {
        return dateToStr(date, "yyyy/MM/dd");
    }
}
